<template>
  <div class="check-task-container">
    <h2>盘点任务</h2>
    
    <el-card class="filter-card">
      <div class="filter-controls">
        <el-select v-model="currentPlan" placeholder="选择盘点计划" @change="changePlan">
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan"
          ></el-option>
        </el-select>
        
        <el-select v-model="assetStatus" placeholder="资产状态" size="small" @change="loadTaskData">
          <el-option label="全部状态" value="all"></el-option>
          <el-option label="未盘点" value="unchecked"></el-option>
          <el-option label="已盘点" value="checked"></el-option>
          <el-option label="差异" value="diff"></el-option>
        </el-select>
        
        <el-input
          v-model="searchKeyword"
          placeholder="搜索资产编号/名称"
          size="small"
          style="width: 200px"
          clearable
          @keyup.enter="loadTaskData"
        >
          <template #append>
            <el-button @click="loadTaskData" size="small"><i class="el-icon-search"></i></el-button>
          </template>
        </el-input>
        
        <el-button type="primary" size="small" @click="batchCheckAssets">批量盘点</el-button>
        <el-button type="success" size="small" @click="autoCheckAssets">自动盘点</el-button>
      </div>
    </el-card>
    
    <el-card class="task-info-card">
      <div class="task-info">
        <div class="info-item">
          <span class="info-label">当前计划：</span>
          <span class="info-value">{{ currentPlan?.planName || '请选择计划' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">开始时间：</span>
          <span class="info-value">{{ currentPlan?.startDate || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">结束时间：</span>
          <span class="info-value">{{ currentPlan?.endDate || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">计划总数：</span>
          <span class="info-value">{{ totalAssets }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">已盘数量：</span>
          <span class="info-value">{{ checkedAssets }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">完成率：</span>
          <span class="info-value">{{ completionRate }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">差异数量：</span>
          <span class="info-value diff-count">{{ diffAssets }}</span>
        </div>
      </div>
      
      <el-progress :percentage="parseInt(completionRate)" :stroke-width="20" :show-text="true"></el-progress>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        :data="taskData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <el-table-column prop="assetNo" label="资产编号" width="150" fixed="left"></el-table-column>
        <el-table-column prop="assetName" label="资产名称" width="200"></el-table-column>
        <el-table-column prop="assetType" label="资产类型" width="120"></el-table-column>
        <el-table-column prop="deptName" label="所属部门" width="120"></el-table-column>
        <el-table-column prop="location" label="存放位置" width="150"></el-table-column>
        <el-table-column prop="supplier" label="供应商" width="120"></el-table-column>
        <el-table-column prop="purchaseDate" label="购买日期" width="120"></el-table-column>
        <el-table-column prop="originalValue" label="原值(元)" width="100" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.originalValue) }}
          </template>
        </el-table-column>
        <el-table-column prop="checkStatus" label="盘点状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.checkStatus)">
              {{ getStatusText(scope.row.checkStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkUser" label="盘点人" width="100"></el-table-column>
        <el-table-column prop="checkTime" label="盘点时间" width="150"></el-table-column>
        <el-table-column prop="checkResult" label="盘点结果" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.checkResult" :type="getResultTagType(scope.row.checkResult)">
              {{ getResultText(scope.row.checkResult) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="checkAsset(scope.row)"
              v-if="scope.row.checkStatus === 'unchecked'"
            >
              盘点
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="viewCheckDetail(scope.row)"
              v-else
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 盘点对话框 -->
    <el-dialog
      v-model="checkDialogVisible"
      title="资产盘点"
      width="600px"
      @close="resetCheckForm"
    >
      <el-form :model="checkForm" label-width="100px">
        <el-form-item label="资产编号">
          <el-input v-model="checkForm.assetNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="资产名称">
          <el-input v-model="checkForm.assetName" disabled></el-input>
        </el-form-item>
        <el-form-item label="资产类型">
          <el-input v-model="checkForm.assetType" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-input v-model="checkForm.deptName" disabled></el-input>
        </el-form-item>
        <el-form-item label="存放位置" required>
          <el-input v-model="checkForm.location"></el-input>
        </el-form-item>
        <el-form-item label="盘点状态" required>
          <el-radio-group v-model="checkForm.checkResult">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="locationDiff">位置不符</el-radio>
            <el-radio label="statusDiff">状态不符</el-radio>
            <el-radio label="loss">盘亏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="盘点备注">
          <el-input type="textarea" v-model="checkForm.remark" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCheck">确认盘点</el-button>
      </template>
    </el-dialog>
    
    <!-- 批量盘点对话框 -->
    <el-dialog
      v-model="batchCheckDialogVisible"
      title="批量盘点"
      width="600px"
      @close="resetBatchCheckForm"
    >
      <el-form :model="batchCheckForm" label-width="100px">
        <el-form-item label="盘点状态" required>
          <el-radio-group v-model="batchCheckForm.checkResult">
            <el-radio label="normal">全部正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="盘点备注">
          <el-input type="textarea" v-model="batchCheckForm.remark" :rows="3"></el-input>
        </el-form-item>
        <div class="selected-count">
          已选择 {{ selectedAssets.length }} 条记录
        </div>
      </el-form>
      <template #footer>
        <el-button @click="batchCheckDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchCheck" :disabled="selectedAssets.length === 0">
          确认批量盘点
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

export default {
  name: 'CheckTask',
  setup() {
    const currentPlan = ref(null)
    const assetStatus = ref('all')
    const searchKeyword = ref('')
    const planList = ref([])
    const taskData = ref([])
    const selectedAssets = ref([])
    
    // 分页数据
    const pagination = ref({
      currentPage: 1,
      pageSize: 20,
      total: 0
    })
    
    // 对话框状态
    const checkDialogVisible = ref(false)
    const batchCheckDialogVisible = ref(false)
    
    // 表单数据
    const checkForm = ref({})
    const batchCheckForm = ref({
      checkResult: 'normal',
      remark: ''
    })
    
    // 统计数据
    const totalAssets = ref(0)
    const checkedAssets = ref(0)
    const diffAssets = ref(0)
    const completionRate = ref('0%')
    
    // 加载盘点计划列表
    const loadPlanList = async () => {
      try {
        const response = await axios.get('/api/check/plans')
        if (response.code === 200 && response.data) {
          planList.value = response.data
          if (planList.value.length > 0) {
            currentPlan.value = planList.value[0]
            loadTaskData()
          }
        } else {
          // 使用模拟数据
          setMockPlanList()
        }
      } catch (error) {
        console.error('获取盘点计划列表失败:', error)
        setMockPlanList()
      }
    }
    
    // 设置模拟计划数据
    const setMockPlanList = () => {
      planList.value = [
        {
          id: 1,
          planName: '2024年11月月度盘点',
          startDate: '2024-11-01',
          endDate: '2024-11-05',
          planStatus: '进行中'
        },
        {
          id: 2,
          planName: '2024年第四季度盘点',
          startDate: '2024-10-15',
          endDate: '2024-12-31',
          planStatus: '进行中'
        },
        {
          id: 3,
          planName: 'IT部门专项盘点',
          startDate: '2024-09-10',
          endDate: '2024-09-15',
          planStatus: '进行中'
        }
      ]
      
      if (planList.value.length > 0) {
        currentPlan.value = planList.value[0]
        loadTaskData()
      }
    }
    
    // 加载任务数据
    const loadTaskData = async () => {
      try {
        if (!currentPlan.value) return
        
        const params = {
          planId: currentPlan.value.id,
          status: assetStatus.value === 'all' ? '' : assetStatus.value,
          keyword: searchKeyword.value,
          page: pagination.value.currentPage,
          pageSize: pagination.value.pageSize
        }
        
        const response = await axios.get('/api/check/tasks', {
          params
        })
        
        if (response.code === 200 && response.data) {
          taskData.value = response.data.list
          pagination.value.total = response.data.total
          updateStatistics(response.data.statistics)
        } else {
          // 使用模拟数据
          setMockTaskData()
        }
      } catch (error) {
        console.error('获取盘点任务数据失败:', error)
        setMockTaskData()
      }
    }
    
    // 设置模拟任务数据
    const setMockTaskData = () => {
      // 生成模拟数据
      const mockData = []
      const assetTypes = ['笔记本电脑', '台式电脑', '显示器', '打印机', '办公桌椅', '投影仪']
      const deptNames = ['IT部门', '财务部', '人力资源部', '市场部', '行政部', '研发部']
      const locations = ['A栋3楼', 'B栋2楼', 'C栋1楼', 'A栋2楼', 'B栋3楼', 'C栋2楼']
      const suppliers = ['联想', '戴尔', 'HP', '华为', '苹果', '小米']
      
      for (let i = 1; i <= 50; i++) {
        const status = i <= 30 ? 'checked' : i <= 40 ? 'diff' : 'unchecked'
        const result = status === 'diff' ? ['locationDiff', 'statusDiff', 'loss'][Math.floor(Math.random() * 3)] : status === 'checked' ? 'normal' : null
        
        mockData.push({
          id: i,
          assetNo: `ZC${String(i).padStart(6, '0')}`,
          assetName: `${assetTypes[Math.floor(Math.random() * assetTypes.length)]}${Math.floor(Math.random() * 1000)}`,
          assetType: assetTypes[Math.floor(Math.random() * assetTypes.length)],
          deptName: deptNames[Math.floor(Math.random() * deptNames.length)],
          location: locations[Math.floor(Math.random() * locations.length)],
          supplier: suppliers[Math.floor(Math.random() * suppliers.length)],
          purchaseDate: `202${Math.floor(Math.random() * 4)}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
          originalValue: (Math.random() * 20000 + 1000).toFixed(2),
          checkStatus: status,
          checkUser: status !== 'unchecked' ? `用户${Math.floor(Math.random() * 10) + 1}` : '',
          checkTime: status !== 'unchecked' ? `2024-11-${String(Math.floor(Math.random() * 5) + 1).padStart(2, '0')} ${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}` : '',
          checkResult: result
        })
      }
      
      // 根据筛选条件过滤数据
      let filteredData = [...mockData]
      if (assetStatus.value !== 'all') {
        filteredData = filteredData.filter(item => item.checkStatus === assetStatus.value)
      }
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        filteredData = filteredData.filter(item => 
          item.assetNo.toLowerCase().includes(keyword) || 
          item.assetName.toLowerCase().includes(keyword)
        )
      }
      
      // 分页处理
      const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
      const end = start + pagination.value.pageSize
      taskData.value = filteredData.slice(start, end)
      pagination.value.total = filteredData.length
      
      // 更新统计数据
      totalAssets.value = mockData.length
      checkedAssets.value = mockData.filter(item => item.checkStatus === 'checked').length
      diffAssets.value = mockData.filter(item => item.checkStatus === 'diff').length
      completionRate.value = totalAssets.value > 0 ? 
        Math.round((checkedAssets.value / totalAssets.value) * 100) + '%' : '0%'
    }
    
    // 更新统计数据
    const updateStatistics = (statistics) => {
      totalAssets.value = statistics.totalAssets || 0
      checkedAssets.value = statistics.checkedAssets || 0
      diffAssets.value = statistics.diffAssets || 0
      completionRate.value = statistics.completionRate || '0%'
    }
    
    // 切换计划
    const changePlan = () => {
      pagination.value.currentPage = 1
      loadTaskData()
    }
    
    // 选中项变化
    const handleSelectionChange = (selection) => {
      selectedAssets.value = selection
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      pagination.value.currentPage = 1
      loadTaskData()
    }
    
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      loadTaskData()
    }
    
    // 资产盘点
    const checkAsset = (asset) => {
      checkForm.value = {
        ...asset,
        remark: ''
      }
      checkDialogVisible.value = true
    }
    
    // 确认盘点
    const confirmCheck = async () => {
      try {
        const checkData = {
          id: checkForm.value.id,
          location: checkForm.value.location,
          checkResult: checkForm.value.checkResult,
          remark: checkForm.value.remark
        }
        
        // 模拟API调用
        console.log('盘点资产:', checkData)
        
        checkDialogVisible.value = false
        loadTaskData()
        
        ElMessage.success('盘点成功')
      } catch (error) {
        console.error('盘点失败:', error)
        ElMessage.error('盘点失败')
      }
    }
    
    // 批量盘点
    const batchCheckAssets = () => {
      if (selectedAssets.value.length === 0) {
        ElMessage.warning('请先选择要盘点的资产')
        return
      }
      batchCheckDialogVisible.value = true
    }
    
    // 确认批量盘点
    const confirmBatchCheck = async () => {
      try {
        const assetIds = selectedAssets.value.map(asset => asset.id)
        const checkData = {
          assetIds,
          checkResult: batchCheckForm.checkResult,
          remark: batchCheckForm.remark
        }
        
        // 模拟API调用
        console.log('批量盘点资产:', checkData)
        
        batchCheckDialogVisible.value = false
        selectedAssets.value = []
        loadTaskData()
        
        ElMessage.success('批量盘点成功')
      } catch (error) {
        console.error('批量盘点失败:', error)
        ElMessage.error('批量盘点失败')
      }
    }
    
    // 自动盘点
    const autoCheckAssets = () => {
      ElMessageBox.confirm('确定要自动盘点所有未盘点的资产吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 模拟API调用
          console.log('自动盘点资产')
          
          loadTaskData()
          ElMessage.success('自动盘点完成')
        } catch (error) {
          console.error('自动盘点失败:', error)
          ElMessage.error('自动盘点失败')
        }
      }).catch(() => {})
    }
    
    // 查看盘点详情
    const viewCheckDetail = (asset) => {
      checkForm.value = { ...asset }
      checkDialogVisible.value = true
    }
    
    // 重置盘点表单
    const resetCheckForm = () => {
      checkForm.value = {}
    }
    
    // 重置批量盘点表单
    const resetBatchCheckForm = () => {
      batchCheckForm.value = {
        checkResult: 'normal',
        remark: ''
      }
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const statusMap = {
        'unchecked': 'warning',
        'checked': 'success',
        'diff': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'unchecked': '未盘点',
        'checked': '已盘点',
        'diff': '差异'
      }
      return statusMap[status] || '未知'
    }
    
    // 获取结果标签类型
    const getResultTagType = (result) => {
      const resultMap = {
        'normal': 'success',
        'locationDiff': 'warning',
        'statusDiff': 'warning',
        'loss': 'danger'
      }
      return resultMap[result] || 'info'
    }
    
    // 获取结果文本
    const getResultText = (result) => {
      const resultMap = {
        'normal': '正常',
        'locationDiff': '位置不符',
        'statusDiff': '状态不符',
        'loss': '盘亏'
      }
      return resultMap[result] || '未知'
    }
    
    // 格式化金额
    const formatCurrency = (value) => {
      return parseFloat(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }
    
    onMounted(() => {
      loadPlanList()
    })
    
    return {
      currentPlan,
      assetStatus,
      searchKeyword,
      planList,
      taskData,
      selectedAssets,
      pagination,
      checkDialogVisible,
      batchCheckDialogVisible,
      checkForm,
      batchCheckForm,
      totalAssets,
      checkedAssets,
      diffAssets,
      completionRate,
      changePlan,
      loadTaskData,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      checkAsset,
      confirmCheck,
      batchCheckAssets,
      confirmBatchCheck,
      autoCheckAssets,
      viewCheckDetail,
      resetCheckForm,
      resetBatchCheckForm,
      getStatusTagType,
      getStatusText,
      getResultTagType,
      getResultText,
      formatCurrency
    }
  }
}
</script>

<style scoped>
.check-task-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-controls .el-select {
  width: 200px;
}

.task-info-card {
  margin-bottom: 20px;
}

.task-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  color: #909399;
  margin-right: 5px;
}

.info-value {
  color: #303133;
  font-weight: 500;
}

.diff-count {
  color: #f56c6c;
  font-weight: bold;
}

.table-card {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.selected-count {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}
</style>